import { searchApi } from "@/api/api";
// 防抖动
import {debounce}from "@/common/utils"
export default {
  name: "search",
  data() {
    return {
      value: "",
      searchList: [],
      searchHistory: [],
      hot_search: "海贼王",
    };
  },
  components: {},
  created() {
    // 查看本地记录是否存有数据
    let searchHistory = localStorage.getItem("searchHistory");
    // 如果有数据则拿出
    if (searchHistory) {
      this.searchHistory = JSON.parse(searchHistory) || [];
    }
  },
  methods: {
    //点击enter或搜索开始搜索
    onsearch_true(e) {
      e = e.trim();
      e = e || this.hot_search;
      this.search_result_click(e);
      // console.log(e)
    },

    // 防抖动
    onSearch: debounce(function (val) {
      console.log(val);

      val = val.trim();
      // 搜索框没有数据就return
      if (val.length === 0) {
        this.searchList = [];
        return;
      }
      searchApi({
        // 搜索框有数据就继续搜索
        key_word: val,
      }).then((res) => {
        if (res.code == 0) {
          this.searchList = res.data;
        }
      });
    }),

    // 点击搜索结果
    search_result_click(title) {
      title = title.trim();
      // 判断是否拥有重复记录  如有则删掉
      let index = this.searchHistory.findIndex((v) => v === title);
      if (index >= 0) {
        this.searchHistory.splice(index, 1);
      }

      // 本地记录
      this.searchHistory.unshift(title);

      // 倒序排布
      localStorage.setItem("searchHistory", JSON.stringify(this.searchHistory));
                        // 搜索列表
      this.$router.push("/searchList?key_word=" + title);
    },

    // 删除单个历史记录
    search_del(index) {
      this.searchHistory.splice(index, 1);
      localStorage.setItem(
        "searchHistory",
        JSON.stringify(this.searchHistory)
      ) / [];
    },

    // 删除全部历史记录
    search_all_del(index) {
      this.searchHistory = [];
      localStorage.setItem("searchHistory", JSON.stringify([])) / [];
    },
    // 点击历史记录跳转
    search_history_click(title) {
      this.search_result_click(title);
    },
  },
};